<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-07-26
 * Time: 14:29
 */

namespace App\Repositories;


use App\Models\User;
use App\Models\UserAuthentication;
use Illuminate\Support\Arr;

/**
 * 遵循SOLID原则（分割、单元测试、mock测试）
 * 基于User model的数据库逻辑
 * Class UserRepository
 * @package App\Repositories
 */
class UserRepository
{
    /**
     * @var User 注入的User model
     */
    protected $user;

    /**
     * @var UserAuthentication
     */
    protected $userAuthentication;

    /**
     * UserRepository constructor.
     * @param User $user
     */
    public function __construct(User $user,
                                UserAuthentication $userAuthentication){
        $this->user = $user;
        $this->userAuthentication = $userAuthentication;
    }

    /**
     * 获取用户列表
     * @param array $arrData
     * @param int $limit
     * @return mixed
     */
    public function getUserPage(array $arrData, $realStatue, $limit){
        return $this->user
            ->with(['totalIntegral', 'totalAmount', 'authentication',
                'fanNum'=>function($q){
                $q->select('id', 'parentId')->withCount('fanNum as fanNums');
            }])
            ->when($arrData, function ($q)use($arrData){
                $q->where($arrData);
            })
            ->when(!is_null($realStatue), function ($q)use($realStatue){
                $q->whereHas( 'authentication', function ($q) use($realStatue){
                    $q->where('real_status', $realStatue);
                });
            })
            ->withCount(['loginLog as login_log', 'fanNum as fanNums'])
            ->withTrashed()
            ->paginate($limit);
    }

    /**
     * 软删除管理员
     * @param $id
     * @return int
     */
    public function deleteManageUser($id){
        return $this->user->destroy(array($id));
    }

    /**
     * 根据id获取用户信息
     * @param int $userId
     * @return mixed
     */
    public function getUserById(int $userId){
        return $this->user->findOrFail($userId);
    }

    /**
     * 返回管理员列表
     * @param array $arrData
     * @param $limit
     * @return mixed
     */
    public function getManageUserPage(array $arrData, $limit){
        return $this->user
            ->whereHas('role')
            ->when($arrData, function ($q)use($arrData){
                $q->where($arrData);
            })
            ->withCount('loginLog as login_log')
            ->paginate($limit);
    }

    /**
     * 编辑管理员
     * @param array $data
     * @return mixed
     */
    public function updateManageUser(array $data){
        $manage = $this->user->findOrFail($data['id']);

        $manage->username = $data['username'];
        $manage->realname = $data['username'];
        $manage->mobile = $data['mobile'];
        $manage->user_type = $data['user_type'];
        $manage->password = app('hash')->make($data['password']);
        $manage->gender = $data['gender'];
        Arr::has($data, 'signature') && $manage->signature = $data['mobile'];

        $manage->saveOrFail();

        return $manage;
    }

    /**
     * 新增管理员
     * @param array $data
     * @return mixed
     */
    public function addManageUser(array $data){
        $this->user->username = $data['username'];
        $this->user->realname = $data['username'];
        $this->user->mobile = $data['mobile'];
        $this->user->user_type = $data['user_type'];
        $this->user->password = app('hash')->make($data['password']);
        $this->user->gender = $data['gender'];
        Arr::has($data, 'signature') && $this->user->signature = $data['mobile'];

        $this->user->saveOrFail();

        return $this->user;
    }

    /**
     * 处理用户状态
     * @param int $id
     * @param int $status
     * @return mixed
     */
    public function handleManageUser(int $id, int $status){
        $user = $this->user->findOrFail($id);

        $user->status = $status;

        $user->saveOrFail();

        return $user;
    }

    /**
     * 获取用户实名认证信息
     * @param $userId
     * @return mixed
     */
    public function getUserAuthentication($userId){
        return $this->userAuthentication->where('userId',$userId)->get();
    }

    /**
     * 删除用户
     * @param array $ids
     * @return int
     */
    public function deleteUserRepository(array $ids){
        return $this->user->destroy($ids);
    }

    /**
     * 恢复被删除用户
     * @param int $id
     * @return mixed
     */
    public function recoveryUserRepository(int $id){
        return $this->user
            ->where('id', $id)
            ->restore();
    }

    /**
     * 获取用户总数
     * @return mixed
     */
    public function getUserCountRepository(){
        return $this->user->count();
    }

    /**
     * 获取所有用户的信息
     * @return mixed
     */
    public function getAllUserRepository(){
        return $this->user
            ->select(['id', 'nickname', 'realname', 'phone'])
            ->get();
    }
}
